package com.woniu.inlet.listen;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniu.adapter.DailyCodeValuationAdapter;
import com.woniu.adapter.GoldFundSellAdapter;
import com.woniu.outlet.client.OrderMessage;
import com.woniu.outlet.client.UpdateOrderStatus;
import com.woniu.outlet.mysql.ReceivedMsgFGSellDao;
import com.woniu.outlet.mysql.po.DailyCodeTOne;
import com.woniu.outlet.mysql.po.ReceivedMsgFGSellMySQL;
import com.woniu.service.bean.GoldFundSell;
import com.woniu.util.AppUtils;
import com.woniu.util.DateUtil;
import com.woniu.util.IsWorkingDayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 监听黄金基金的卖出
 */
@Slf4j
@Component
@RabbitListener(queues = "order_sell_fg_pay")
public class GoldFundSellOrderListener {

    @Autowired
    private ReceivedMsgFGSellDao receivedMsgFGSellDao;
    @Autowired
    private UpdateOrderStatus updateOrderStatus;
    @Autowired
    private GoldFundSellAdapter goldFundSellAdapter;
    @Autowired
    private DailyCodeValuationAdapter dailyCodeValuationAdapter;
    @Autowired
    private OrderMessage orderMessage;

    @Transactional // 抛出异常，事务回滚
    @RabbitHandler
    public void handle(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {
        String[] strings = message.split("!");
        if (strings.length < 2) {
            channel.basicReject(tag, false);
            throw new RuntimeException("接收到的消息内容格式错误");
        }

        //消息的第一部分是消息的id
        String messageIdString = strings[0];
        Integer messageId = Integer.parseInt(messageIdString);

        //消息的第二部分是消息的具体内容
        String substring = strings[1];

        try {
            // 1. 判断是否是重复消息：insert into 去重表
            receivedMsgFGSellDao.insert(new ReceivedMsgFGSellMySQL(null, messageId));
        } catch (RuntimeException e) {
            log.debug("该消息重复");
            // 2. 拒绝消息。要求 RabbitMQ 从队列中删除。
            channel.basicReject(tag, false);
            return;
        }

        try {
            // 执行本地业务逻辑
            log.debug("执行本地业务逻辑");
            GoldFundSell goldFundSell = new GoldFundSell();
            LinkedMultiValueMap<String,String> object = JSON.parseObject(substring, LinkedMultiValueMap.class);
            String sid="";
            for (String id : object.keySet()) {
                if (id.equals("sell")) {
                    List<String> sells = object.get(id);
                    sid=sells.get(0);
                }
            }
            for (String id : object.keySet()) {
                if (id.equals("sell")) {
                   continue;
                }
                List<String> strings1 = object.get(id);
                log.debug("该用户的产品卖出信息：{}",strings1);
                String join = StringUtils.join(strings1.toArray(), "/");

                String[] split = join.split("/");
                goldFundSell.setCodeId(split[0]);
                goldFundSell.setSellSale(new BigDecimal(split[1]));
                goldFundSell.setSchedule(split[2]);
                goldFundSell.setOrderId(Integer.valueOf(id));
                goldFundSell.setSId(Integer.valueOf(sid));
                goldFundSell.setUserId(Integer.valueOf(split[3])); //用户id
                goldFundSell.setDealPrice(new BigDecimal(split[4])); //用户本金
                goldFundSell.setProductType(split[5]); //产品类型
                //计算可以卖出的日期
                String sellTime = "";
                //得到当前系统时间
                String timeStr = AppUtils.getTime();
                //判断今天是否是工作日
                String isWorkingDay = IsWorkingDayUtil.getIsWorkingDay(timeStr);
                if(isWorkingDay.equals("y")){
                    //获取当前系统时间的小时数
                    String timeH = AppUtils.getTimeH();
                    if(Integer.valueOf(timeH)<15){
                        //如果当天15点之前卖出则当天可以出售
                        goldFundSell.setSellTime(AppUtils.getTimeg());
                        sellTime = AppUtils.getTimeg();
                    }else{
                        //否者就是当天15点之后卖出的
                        String time = DateUtil.getIncomeDate();
                        goldFundSell.setSellTime(time);
                        sellTime = time;
                    }
                }else{
                    //当天不是工作日
                    //否者就是当天15点之后卖出的
                    String time = DateUtil.getIncomeDate();
                    goldFundSell.setSellTime(time);
                    sellTime = time;
                }
                //添加数据到数据库
                goldFundSellAdapter.AddGoldFundSell(goldFundSell);
                //发送通知给用户
                DailyCodeTOne dailyCodeValuationMySQL = dailyCodeValuationAdapter.getDailyCodeValuationMySQL(split[0]);
                String inform = "您好，您有一笔订单:["+dailyCodeValuationMySQL.getName()+"]等待卖出,我们将在成功卖出以后通知您。"+split[3]+"y";
                orderMessage.sendMessage("pay.inform.user", "pay_inform_user", inform);
                while (true){
                    try{
                        updateOrderStatus.revocationDate(sid,sellTime);
                        break;
                    }catch (Exception e){
                        log.debug("openfeign失败");
                    }
                }
            }
        }catch (RuntimeException e) {
            // 执行本地业务出错，拒绝消息，要求 RabbitMQ 从队列中删除。
            // 等待发送者的定时器下次再发送一次。
            channel.basicReject(tag, false);
            throw new NullPointerException();
        }
    }

}
